package jp.sinya.temicontact.mvp.presenter;

import android.os.Handler;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.Collections;
import java.util.List;

import jp.sinya.temicontact.mvp.model.Contact;
import jp.sinya.temicontact.mvp.view.ContactListView;
import jp.sinya.temicontact.net.NetUtils;
import jp.sinya.temicontact.utils.FileUtils;
import jp.sinya.temicontact.utils.LogUtils;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @author Koizumi Sinya
 * @date 2018/01/11. 20:58
 * @edithor
 * @date
 */
public class ContactListPresenter {
    private ContactListView view;
    private List<Contact> contactList;
    private boolean isLoading;
    private boolean isAutoLoad;

    public ContactListPresenter(ContactListView view) {
        this.view = view;
    }

    public List<Contact> getContactList() {
        return contactList;
    }

    public boolean isLoading() {
        return isLoading;
    }

    public void setAutoLoad(boolean autoLoad) {
        isAutoLoad = autoLoad;
    }

    public void request(boolean isAutoLoad) {
        isLoading = true;
        this.isAutoLoad = isAutoLoad;
        view.showLoading();

        //本地测试模拟加载网络
        //requestByLocalTest();

        requestByNet();
    }

    private void requestByLocalTest() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                String jsonArr = FileUtils.getFileFromAssets("contacts_mock_short.json");
                contactList = new Gson().fromJson(jsonArr, new TypeToken<List<Contact>>() {
                }.getType());

                Collections.sort(contactList, new Contact.DateComparator());

                if (isAutoLoad) {
                    view.loadData();
                }

                view.closeLoading();
                isLoading = false;
            }
        }, 500);

    }

    private void requestByNet() {
        NetUtils.getContactList(new Callback<List<Contact>>() {
            @Override
            public void onResponse(Call<List<Contact>> call, Response<List<Contact>> response) {
                contactList = response.body();

                Collections.sort(contactList, new Contact.DateComparator());
                //LogUtils.Sinya(contactList.toString());

                if (isAutoLoad) {
                    view.loadData();
                }

                view.closeLoading();
                isLoading = false;
            }

            @Override
            public void onFailure(Call<List<Contact>> call, Throwable t) {
                LogUtils.Sinya(t.getMessage());

                view.closeLoading();
                view.showError(t.getMessage());
                isLoading = false;
            }
        });
    }
}
